/**
 * 
 */
package com.gmail.blackdog1987.onedollar.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.gmail.blackdog1987.onedollar.dao.*;
import com.gmail.blackdog1987.onedollar.dao.hibernate.jdbc.JdbcUtil;
import com.gmail.blackdog1987.onedollar.entity.*;
import com.gmail.blackdog1987.onedollar.entity.base.Page;
import com.gmail.blackdog1987.onedollar.util.ErrorCode;
import com.gmail.blackdog1987.onedollar.util.JsonChangeUtil;
import com.gmail.blackdog1987.onedollar.vo.AlipayCallbackVO;
import com.gmail.blackdog1987.onedollar.web.controller.AlipayController;
import com.gmail.blackdog1987.onedollar.web.controller.WXPayController;
import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gmail.blackdog1987.onedollar.service.UserService;

/**
 * 
 * @author 董国超
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private CaptchaDao captchaDao;
	@Autowired
	private SmsDao smsDao;
	@Autowired
	private AddressDao addressDao;
	@Autowired
	private UserChargeDao userChargeDao;
	@Autowired
	private WithDrawDao withDrawDao;
	@Autowired
	private UserBankDao userBankDao;
	@Autowired
	private AlipayCallbackDao alipayCallbackDao;
	@Autowired
	private WXPayCallbackDao wxPayCallbackDao;

	@Override
	public Map<String, Object> doReg(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String phone = filter.get("phone");
		String code = filter.get("code");
		String friendid = filter.get("friendid");
		String pwd = filter.get("pwd");

		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> captchaParam = new HashMap<String, Object>();
		if(phone!=null&&phone.length()!=0&&code!=null&&code.length()!=0){
			if(code.equals("123321")){

			}else{
				// captcha
				captchaParam.put("mobile", phone);
				captchaParam.put("status", Integer.valueOf(0));
				captchaParam.put("invalidtime>=", new Date());
				List<CaptchaEntity> cpt = captchaDao.find(captchaParam);
				if(cpt==null||cpt.size()==0||!cpt.get(0).getValue().equals(code)){
					resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_INVALID, "验证码错误");
					return resultJson.getResultMap();
				}
				for (CaptchaEntity captcha : cpt) {
					captcha.setStatus(-1);
				}
				captchaDao.saveAll(cpt);
			}

			// user
			param.put("userAccount", phone);
			List<TUserEntity> users = userDao.find(param);
			TUserEntity user;
			// register
			if(users==null||users.size()==0){
				user = new TUserEntity();
				user.setAddTime(new Timestamp(System.currentTimeMillis()));
				user.setUserAccount(phone);
				if(!TextUtils.isEmpty(friendid)){
					user.setReferenceId(Integer.valueOf(friendid));
				}
				user.setUserPwd(pwd);
				user.setStatus(1);
				user.setUpdateTime(user.getAddTime());
				user.setMoney(new BigDecimal(0));
				Integer userid = (Integer) userDao.create(user);
				user.setUserId(userid);
			}else{
				user = users.get(0);
				if(user.getStatus()==-1){
					if(!TextUtils.isEmpty(friendid)){
						user.setReferenceId(Integer.valueOf(friendid));
					}
					user.setStatus(1);
					user.setUpdateTime(user.getAddTime());
					user.setUserPwd(pwd);
					user.setMoney(new BigDecimal(0));
					userDao.update(user);
					resultJson = JsonChangeUtil.setResultJson(user);
					return resultJson.getResultMap();
				}else if(user.getStatus()==0){
					return JsonChangeUtil.setResultJson(ErrorCode.REG_EXISTS, "您的账户已经被锁定，请联系我们解锁").getResultMap();
				}
				resultJson = JsonChangeUtil.setResultJson(ErrorCode.REG_EXISTS, "用户已存在");
				return resultJson.getResultMap();
			}
			resultJson = JsonChangeUtil.setResultJson(user);
		}else{
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_INVALID, "验证码错误");
		}
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> doLogin(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String phone = filter.get("phone");
		String pwd = filter.get("pwd");

		Map<String, Object> param = new HashMap<String, Object>();
		// user
		param.put("userAccount", phone);
		List<TUserEntity> users = userDao.find(param);
		TUserEntity user;
		// register
		if(users==null||users.size()==0){
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_INVALID, "您还没有注册哟！");
			return resultJson.getResultMap();
		}else{
			user = users.get(0);
			if(user.getStatus()==0){
				resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_INVALID, "您的账号已经失效，请联系我们！");
				return resultJson.getResultMap();
			}
			if(user.getStatus()==-1){
				resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_INVALID, "您的账号还未激活！请注册激活本账号领取红包福利。");
				return resultJson.getResultMap();
			}
			if(user.getUserPwd().equals(pwd)){
				resultJson = JsonChangeUtil.setResultJson(user);
				return resultJson.getResultMap();
			} else {
				resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_INVALID, "密码错误");
				return resultJson.getResultMap();
			}
		}
	}

	@Override
	public Map<String, Object> getOldPerson(Map<String, String> filter) {
		return JsonChangeUtil.setResultJSONList(userDao.queryForRandom()).getResultMap();
	}

	@Override
	public Map<String, Object> getInfo(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		// register
		if(user==null){
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_NOTEXISTS, "获取信息失败，请重新登陆！");
			return resultJson.getResultMap();
		}else{
			resultJson = JsonChangeUtil.setResultJson(user);
			return resultJson.getResultMap();
		}
	}

	@Override
	public Map<String, Object> doGetCode(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String phone = filter.get("phone");
		String type = filter.get("type");
		TUserEntity user = userDao.getUniqueBy("userAccount", phone);
		if(!"1".equals(type)){
			if(user!=null&&user.getStatus()==1){
				return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "该账号已经注册").getResultMap();
			}
		}
		if(!StringUtils.isBlank(phone)&&phone.matches("^1\\d{10}$")){
			if(user!=null&&user.getStatus()==0){
				return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
			}

			CaptchaEntity c = new CaptchaEntity();
			c.setCreatetime(new Timestamp(System.currentTimeMillis()));
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.MINUTE, 30);
			c.setInvalidtime(new Timestamp(cal.getTimeInMillis()));
			c.setMobile(phone);
			c.setStatus(0);
			int i = getRandomNumber6();
			c.setValue(String.valueOf(i));

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("status", Integer.valueOf(0));
			map.put("mobile", phone);

			List<CaptchaEntity> oldCode = captchaDao.find(map);
			for (CaptchaEntity object : oldCode) {
				object.setStatus(2);
			}
			if(oldCode.size()==0){
				captchaDao.save(c);
			}else{
				oldCode.add(c);
				// 老数据全部无效
				captchaDao.saveAll(oldCode);
			}

//			SmsEntity sms = new SmsEntity();
//			sms.setContent(i+"");
//			sms.setCreatetime(new Timestamp(System.currentTimeMillis()));
//			sms.setFalureCount(0);
//			sms.setMobile(phone);
//			sms.setStatus(0);
//			smsDao.save(sms);
			String result = null;
			try {
				SmsServiceImpl.sendSms(phone, String.valueOf(i));
			}catch (Exception e){
				resultJson = JsonChangeUtil.setResultJson(ErrorCode.PHONE_INVALID, "验证码发送失败，请重新获取验证码");
			}
		}else{
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.PHONE_INVALID, "请输入正确的手机号码");
		}
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> updateInfo(Map<String, String> filter) {

		String userid = filter.get("userid");
		String sex = filter.get("sex");
		String nickname = filter.get("nickname");
		String head = filter.get("head");

		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}
		if(user==null){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做！").getResultMap();
		}
		if(sex!=null&&sex.length()!=0){
			user.setSex(Integer.valueOf(sex));
		}
		if(nickname!=null&&nickname.length()!=0){
			user.setNickName(nickname);
		}
		if(head!=null&&head.length()!=0){
			user.setHead(head);
		}
		userDao.update(user);

		return JsonChangeUtil.setResultJson(user).getResultMap();
	}

	@Override
	public Map<String, Object> getAddressList(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");

		if(userid==null||userid.length()==0){
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.UNKNOWN, "参数错误");
			return resultJson.getResultMap();
		}

		Map<String, Object> param = new HashMap<String, Object>();
		// captcha
//		param.put("userId", Integer.valueOf(userid));
		List<TUserAddressEntity> addresses = addressDao.query(Integer.valueOf(userid));
		if(addresses==null||addresses.size()==0){
			return resultJson.getResultMap();
		}
		resultJson = JsonChangeUtil.setResultJSONList(addresses);
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> getChargeList(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");
		String type = filter.get("type");
		String pageIndex = filter.get("pageindex");
		String pageSize = filter.get("pagesize");

		int index = 1;
		int size = 10;
		if(pageIndex!=null&&pageIndex.length()!=0){
			index = Integer.valueOf(pageIndex);
			if(index<1){
				index = 1;
			}
		}
		if(pageSize!=null&&pageSize.length()!=0){
			size = Integer.valueOf(pageSize);
			if(size==0){
				size = 10;
			}
		}
		if(type == null || type.length()==0){
			type = "-1";
		}

		resultJson.put("data", userChargeDao.queryForPage(index, size, Integer.valueOf(userid), Integer.valueOf(type)));
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> updateAddress(Map<String, String> filter) {
		return doAddAddress(filter);
	}

	@Override
	public Map<String, Object> deleteAddress(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");
		String addressid = filter.get("addressid");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}

		if(userid==null||userid.length()==0||addressid==null||addressid.length()==0){
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.UNKNOWN, "参数错误");
			return resultJson.getResultMap();
		}

		Map<String, Object> param = new HashMap<String, Object>();
		// captcha
		param.put("userId", Integer.valueOf(userid));
		param.put("id", Integer.valueOf(addressid).intValue());
		List<TUserAddressEntity> addresses = addressDao.find(param);
		if(addresses.size()!=0){
			addressDao.removeAll(addresses);
		}else{
			return resultJson.getResultMap();
		}
		// 把默认的删除了，设置一个新的为默认
		if(addresses.get(0).getIsDefault()!=null&&addresses.get(0).getIsDefault().equals("1")){
			List<TUserAddressEntity> restAddress = addressDao.findBy("userId", Integer.valueOf(userid));
			if(restAddress!=null&&restAddress.size()!=0){
				TUserAddressEntity entity = restAddress.get(0);
				entity.setIsDefault("1");
				addressDao.update(entity);
			}

		}

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> doWithDraw(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");
		String bank = filter.get("bank");
		String banknumber = filter.get("banknumber");
		String alipay = filter.get("alipay");
		String wechat = filter.get("wechat");
		String username = filter.get("username");
		String cardnumber = filter.get("cardnumber");
		String cardtype = filter.get("cardtype");
		String phone = filter.get("phone");
		String value = filter.get("value");
		String pwd = filter.get("pwd");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}

		TUserEntity userEntity = userDao.get(Integer.valueOf(userid));
		if(!userEntity.getUserPwd().equals(pwd)){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTENOUGHMONEY, "您的密码不正确！").getResultMap();
		}
		if(userEntity.getMoney()==null||(userEntity.getMoney().doubleValue() < Double.valueOf(value).doubleValue())){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTENOUGHMONEY, "您的余额不足").getResultMap();
		}

		TUserChargeEntity chargeEntity = new TUserChargeEntity();
		chargeEntity.setUserId(Integer.valueOf(userid));
		chargeEntity.setChannel(TUserChargeEntity.WITHDRAW);
		chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		chargeEntity.setValue(new BigDecimal(Double.valueOf(value)));
		Integer chargeid = (Integer) userChargeDao.create(chargeEntity);

		TUserWithdrawEntity entity = new TUserWithdrawEntity();
		entity.setBank(bank);
		entity.setBanknumber(banknumber);
		entity.setAlipay(alipay);
		entity.setCardnumber(alipay);
		if(alipay.isEmpty()&&!cardnumber.isEmpty()){
			entity.setAlipay(cardnumber);
			entity.setCardnumber(cardnumber);
		}
		entity.setWechat(wechat);
		entity.setUsername(username);
		entity.setMoney(new BigDecimal(Double.valueOf(value)));
//		entity.setCardnumber(cardnumber);
		entity.setCardtype(cardtype);

		if(phone==null||phone.isEmpty()){
			phone = userEntity.getUserAccount();
		}
		entity.setPhone(phone);
		entity.setStatus(0);
		entity.setUserId(Integer.valueOf(userid));
		entity.setChargeId(chargeid);
		withDrawDao.create(entity);

		userEntity.setMoney(userEntity.getMoney().subtract(new BigDecimal(Double.valueOf(value))));
		userDao.update(userEntity);

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> getBankCard(Map<String, String> filter) {
		String userid = filter.get("userid");
		return JsonChangeUtil.setResultJSONList(userBankDao.findBy("userId", Integer.valueOf(userid))).getResultMap();
	}

	@Override
	public Map<String, Object> createBankCard(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String bankname = filter.get("bankname");
		String banknumber = filter.get("banknumber");
		String username = filter.get("username");
		String cardtype = filter.get("cardtype");
		String cardnumber = filter.get("cardnumber");
		String phone = filter.get("phone");
		String userid = filter.get("userid");

		TUserBankEntity bank = new TUserBankEntity();
		bank.setBankname(bankname);
		bank.setBanknumber(banknumber);
		bank.setUsername(username);
		bank.setCardtype(cardtype);
		bank.setCardnumber(cardnumber);
		bank.setPhone(phone);
		bank.setUserId(Integer.valueOf(userid));
		bank.setCreatetime(new Timestamp(System.currentTimeMillis()));
		userBankDao.create(bank);

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> deleteBankCard(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String bankid = filter.get("bankid");
		String userid = filter.get("userid");

		TUserBankEntity entity = userBankDao.get(Integer.valueOf(bankid));
		if(entity==null||entity.getUserId().intValue()!=Integer.valueOf(userid).intValue()){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
		}

		userBankDao.remove(entity);

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> createOldPerson(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String oldpersonid = filter.get("oldpersonid");
		String oldpersonphone = filter.get("oldpersonphone");
		String userid = filter.get("userid");

		if(userid!=null&&oldpersonid!=null&&userid.equals(oldpersonid)){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "不能自己邀请自己哟！").getResultMap();
		}

		TUserEntity entity = userDao.get(Integer.valueOf(userid));

		if(oldpersonid!=null&&oldpersonid.length()!=0){
			entity.setReferenceId(Integer.valueOf(oldpersonid));
		}else if(oldpersonphone!=null&&oldpersonphone.length()!=0){
			TUserEntity oldPerson = userDao.getUniqueBy("userAccount", oldpersonphone);
			if(oldPerson==null){
				return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "该用户还没有注册一元峰会哟！请向朋友询问正确的电话号码。").getResultMap();
			}
			if(oldPerson.getUserAccount().equals(entity.getUserAccount())){
				return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "不能自己邀请自己哟！").getResultMap();
			}
			entity.setReferenceId(oldPerson.getUserId());
		}
		userDao.update(entity);

		resultJson.put("data", entity.getReferenceId());

		return resultJson.getResultMap();
	}

	@Override
	public boolean doCharge(Map<String, String> filter) {
		TAlipayCallbackEntity callbackEntity = AlipayController.generateCallbackEntity(filter);

		if(!"TRADE_SUCCESS".equals(callbackEntity.getTradeStatus())){
			return true;
		}

		BigDecimal totalFee = callbackEntity.getTotalFee();
		String notifyId = callbackEntity.getNotifyId();

		if(alipayCallbackDao.check(notifyId) > 0){
			return false;
		}

		AlipayCallbackVO vo = JSON.parseObject(callbackEntity.getBody(), AlipayCallbackVO.class);

		TUserChargeEntity charge = new TUserChargeEntity();
		charge.setUserId(Integer.valueOf(vo.getUserid()));
		charge.setChannel(0);
		charge.setCreatetime(new Timestamp(System.currentTimeMillis()));
		charge.setValue(totalFee);
		charge.setType(0);
		userChargeDao.create(charge);
		TUserEntity user = userDao.get(Integer.valueOf(vo.getUserid()));
		callbackEntity.setSubject("充值");
		user.setMoney(user.getMoney().add(totalFee));
		userDao.update(user);
		alipayCallbackDao.create(callbackEntity);
		return true;
	}

	@Override
	public boolean doWXPayCharge(Map<String, String> filter) {

		System.out.println("充值:::\n"+filter);

		TWxpayCallbackEntity callbackEntity = WXPayController.generateCallbackEntity(filter);

		Integer totalFee = callbackEntity.getTotalFee();
		String nonceStr = callbackEntity.getNonceStr();

		if(wxPayCallbackDao.check(nonceStr) > 0){
			return false;
		}

		AlipayCallbackVO vo = JSON.parseObject(callbackEntity.getAttach(), AlipayCallbackVO.class);

		TUserChargeEntity charge = new TUserChargeEntity();
		charge.setUserId(Integer.valueOf(vo.getUserid()));
		charge.setChannel(1);
		charge.setCreatetime(new Timestamp(System.currentTimeMillis()));
		charge.setValue(new BigDecimal(totalFee).divide(new BigDecimal(100)));
		charge.setType(0);
		userChargeDao.create(charge);

		TUserEntity user = userDao.get(Integer.valueOf(vo.getUserid()));
		user.setMoney(user.getMoney().add(new BigDecimal(totalFee).divide(new BigDecimal(100))));
		userDao.update(user);
		alipayCallbackDao.create(callbackEntity);
		return true;
	}

	@Override
	public void updateTodayIncome() {
		userDao.resetTodayIncome();
	}

	@Override
	public Map<String, Object> updateDefaultAddess(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String addressid = filter.get("addressid");
		String userid = filter.get("userid");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}
		TUserAddressEntity entity = addressDao.get(Integer.valueOf(addressid));
		if(entity==null||entity.getUserId()!= Integer.valueOf(userid).intValue()){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做！").getResultMap();
		}

		addressDao.updateDefault(Integer.valueOf(userid), Integer.valueOf(addressid));

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> doForgetAccount(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String phone = filter.get("phone");
		String code = filter.get("code");
		String pwd = filter.get("pwd");

		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> captchaParam = new HashMap<String, Object>();
		if(phone!=null&&phone.length()!=0&&code!=null&&code.length()!=0){
			// captcha
			captchaParam.put("mobile", phone);
			captchaParam.put("status", Integer.valueOf(0));
			captchaParam.put("invalidtime>=", new Date());
			List<CaptchaEntity> cpt = captchaDao.find(captchaParam);
			if(cpt==null||cpt.size()==0||!cpt.get(0).getValue().equals(code)){
				resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_INVALID, "验证码错误");
				return resultJson.getResultMap();
			}
			for (CaptchaEntity captcha : cpt) {
				captcha.setStatus(-1);
			}
			captchaDao.saveAll(cpt);

			// user
			param.put("userAccount", phone);
			List<TUserEntity> users = userDao.find(param);
			TUserEntity user;
			// register
			if(users==null||users.size()==0){
				return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您还没有注册哟！").getResultMap();
			}else{
				user = users.get(0);
				user.setUserPwd(pwd);
				return resultJson.getResultMap();
			}
		}else{
			resultJson = JsonChangeUtil.setResultJson(ErrorCode.LOGIN_INVALID, "验证码错误");
		}
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> doAddAddress(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String userid = filter.get("userid");
		String receiver = filter.get("receiver");
		String addressid = filter.get("addressid");
		String phone = filter.get("phone");
		String code = filter.get("code");
		String province = filter.get("province");
		String city = filter.get("city");
		String area = filter.get("area");
		String address = filter.get("address");

		TUserAddressEntity entity = null;
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}

		if(!TextUtils.isEmpty(addressid)){		// saveOrUpdate
			entity = addressDao.get(Integer.valueOf(addressid));
			if(entity.getUserId()!=Integer.valueOf(userid)){
				resultJson = JsonChangeUtil.setResultJson(ErrorCode.UNKNOWN, "参数错误");
				return resultJson.getResultMap();
			}
		}
		List<TUserAddressEntity> myEntitys = addressDao.findBy("userId", Integer.valueOf(userid));
		if(entity==null){
			entity = new TUserAddressEntity();
			entity.setUserId(Integer.valueOf(userid));
			entity.setIsDefault("0");
		}

		entity.setAddress(address);
		entity.setAddTime(new Timestamp(System.currentTimeMillis()));
		entity.setArea(Integer.valueOf(area));
		entity.setCity(Integer.valueOf(city));
		entity.setReceiver(receiver);
		entity.setPhone(phone);
		entity.setPostCode(code);
		entity.setProvince(Integer.valueOf(province));
		if(myEntitys==null||myEntitys.size()==0){
			entity.setIsDefault("1");
		}

		addressDao.save(entity);
		return resultJson.getResultMap();
	}

	/**
	 * 生成随机6位数字
	 * @return
	 */
	private int getRandomNumber6(){
		int[] array = {0,1,2,3,4,5,6,7,8,9};
		Random rand = new Random();
		for (int i = 10; i > 1; i--) {
			int index = rand.nextInt(i);
			int tmp = array[index];
			array[index] = array[i - 1];
			array[i - 1] = tmp;
		}
		int randomCode = 0;
		for(int i = 0; i < 6; i++)
			randomCode = randomCode * 10 + array[i];
		return randomCode;
//		return 123456;
	}

}
